﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;

namespace PiggyBank
{
    public partial class MainPage : PhoneApplicationPage
    {
        DispatcherTimer selfloop = new DispatcherTimer();
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            selfloop.Stop();
            for (int i = gameCanvas.Children.Count -1; i >= 0; i--)
            {
                var item = gameCanvas.Children[i] as IDisposable;
                if (item != null)
                    item.Dispose();
                gameCanvas.Children.RemoveAt(i);
            }
            
            base.OnNavigatedFrom(e);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            selfloop.Start();
            base.OnNavigatedTo(e);
        }
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= MainPage_Loaded;
            selfloop.Tick += new EventHandler(selfloop_Tick);
            selfloop.Interval = TimeSpan.FromMilliseconds(500);
            selfloop.Start();
        }
        Random random = new Random((int)DateTime.Now.Ticks);
        void selfloop_Tick(object sender, EventArgs e)
        {
            AddGold();
        }

        private void StartGame_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/PiggyBank;component/Game.xaml", UriKind.Relative));
        }

        private void test_click(object sender, System.Windows.RoutedEventArgs e)
        {
            AddGold();
        }
        void AddGold()
        {
            var gold = new Gold();
            int mx = 12;
            gold.Speed = mx / 2 - (random.NextDouble() + random.Next(0, mx));
            gold.JumpEndY = -100 - random.Next(0, 65);
            gameCanvas.Children.Add(gold);
            gold.X = 200;
            gold.Y = 600;
            gold.BeginMove();
        }
    }
}
